//
//  PPLoginViewController.m
//  pickpic
//
//  Created by Jinxiao on 8/21/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPLoginViewController.h"
#import "PPRegisterViewController.h"
#import "PPHomeViewController.h"
#import "PPHomeNavigationController.h"

#import "PPNetworkService.h"

#import "PPSocializationManager.h"
#import "PPRetrieveViewController.h"

#define PPINPUTHTEXT_H 60
#define PPLine_H 1


@interface PPLoginViewController () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *accountField;
@property (weak, nonatomic) IBOutlet UITextField *passwordField;
@property (readwrite, nonatomic, strong) UIButton *hiddenButton;
//@property (readwrite, nonatomic, strong) UIButton *loginButton;
@property (readwrite, nonatomic, strong) DGAlignmentButton *qqButton;
@property (readwrite, nonatomic, strong) DGAlignmentButton *wxButton;
@property (readwrite, nonatomic, strong) DGAlignmentButton *wbButton;
//@property (readwrite, nonatomic, strong) UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (readwrite, nonatomic, assign) CGFloat keyboardTop;

//键盘属性
@property (nonatomic, assign) NSTimeInterval  time;
@property (nonatomic, assign) NSUInteger  curve;
@property (nonatomic, assign) CGFloat  keyboardHeight;
@end

@implementation PPLoginViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)exitKeyBoard:(id)sender{

      [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
    
}
- (void)setShowKeyBoard:(BOOL)showKeyBoard{

    if (showKeyBoard) {
        [_accountField becomeFirstResponder];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _keyboardTop = self.view.height;

    self.title = @"登录";

    self.view.backgroundColor = [UIColor whiteColor];

    self.navigationItem.leftBarButtonItem = nil;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(exitKeyBoard:)];
    [self.view addGestureRecognizer:tap];
    
//    __weak typeof(self) weakSelf = self;
//    [self setNavigationRightTitle:@"注册" titleColor:[UIColor colorWithRGBHex:0xffdd17]  action:^{
//
//        [MobClick event:@"1"];
//
//        PPRegisterViewController *registerViewController = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateViewControllerWithIdentifier:@"PPRegisterViewController"];
//        [weakSelf.navigationController pushViewController:registerViewController animated:YES];
//
//    }];

    {
//        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        leftView.backgroundColor = [UIColor blueColor];
        
//        _accountField.leftView = leftView;
//        _accountField.leftViewMode = UITextFieldViewModeAlways;

        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
        rightView.backgroundColor = [UIColor clearColor];
        _accountField.rightView = rightView;
        _accountField.rightViewMode = UITextFieldViewModeAlways;

        dispatch_async(dispatch_get_main_queue(), ^{
//            [_accountField becomeFirstResponder];
        });
    }

    {
//        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 16, 1)];
//        leftView.backgroundColor = [UIColor clearColor];
//        _passwordField.leftView = leftView;
//        _passwordField.leftViewMode = UITextFieldViewModeAlways;

        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 48, 46)];
        rightView.backgroundColor = [UIColor clearColor];
        _passwordField.rightView = rightView;
        _passwordField.rightViewMode = UITextFieldViewModeAlways;

        _hiddenButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _hiddenButton.adjustsImageWhenHighlighted = NO;
        [_hiddenButton setImage:[UIImage imageNamed:@"code-off"] forState:UIControlStateNormal];
        [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateHighlighted|UIControlStateSelected];
        [_hiddenButton setImage:[UIImage imageNamed:@"code-on"] forState:UIControlStateSelected];
        [_hiddenButton sizeToFit];
        _hiddenButton.center = CGPointMake(rightView.width/2, rightView.height/2);
        _hiddenButton.bounds = CGRectMake(0, 0, 50, 60);
        [_hiddenButton addTarget:self action:@selector(hiddenButtonDidPressed:) forControlEvents:UIControlEventTouchUpInside];
        [rightView addSubview:_hiddenButton];
    }

//    _bottomView = [[UIView alloc] init];
//    _bottomView.backgroundColor = [UIColor clearColor];
//    _bottomView.frame = CGRectMake(0,self.view.height - 90, self.view.width, 90);
//    [self.view addSubview:_bottomView];

//    _loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    _loginButton.enabled = NO;
//    [_loginButton setTitle:@"登录" forState:UIControlStateNormal];
//    [_loginButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xffdd17]] stretchableImageByCenter] forState:UIControlStateNormal];
//    [_loginButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xf9d430]] stretchableImageByCenter] forState:UIControlStateHighlighted];
//    [_loginButton setBackgroundImage:[[UIImage imageWithColor:[UIColor colorWithRGBHex:0xf2f2f2]] stretchableImageByCenter] forState:UIControlStateDisabled];
//    [_loginButton addTarget:self action:@selector(loginButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
//    [_bottomView addSubview:_loginButton];
//    self.bottomView.backgroundColor =RED;
    
//    CGFloat pading = 0;
//    CGFloat iconW = (SCREEN_WIDTH - 2*20)/3;
    
//    _bottomView.backgroundColor = RED;
    
//    CGFloat iconW = (SCREEN_WIDTH-100)/3;
//    CGFloat h = self.bottomView.height;
    
    _qqButton = [DGAlignmentButton buttonWithType:UIButtonTypeCustom];
    
//    _qqButton.spacing = 10;
//    _qqButton.backgroundColor = BLACK;
//    _qqButton.style = DGAlignmentButtonStyleImageLeft;
    //    _qqButton.contentEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
    //    _qqButton.titleLabel.font = [UIFont systemFontOfSize:12];
    //    [_qqButton setTitleColor:[UIColor colorWithRGBHex:0x2c3c78] forState:UIControlStateNormal];
    //    [_qqButton setTitle:@"QQ登录" forState:UIControlStateNormal];
    [_qqButton setImage:[UIImage imageNamed:@"login_qqicon"] forState:UIControlStateNormal];
    [_qqButton addTarget:self action:@selector(qqButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
        [_qqButton sizeToFit];
    [_bottomView addSubview:_qqButton];
    
    
    
    if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin]) {
        _wxButton = [DGAlignmentButton buttonWithType:UIButtonTypeCustom];
//        _wxButton.frame = CGRectMake(0, 0, iconW, h);
//        _wxButton.spacing = 10;

//        _wxButton.backgroundColor = BLUE;
//        _wxButton.style = DGAlignmentButtonStyleImageLeft;
//        _wxButton.contentEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
//        _wxButton.titleLabel.font = [UIFont systemFontOfSize:12];
////        [_wxButton setTitle:@"微信登录" forState:UIControlStateNormal];
//        [_wxButton setTitleColor:[UIColor colorWithRGBHex:0x2c3c78] forState:UIControlStateNormal];
        [_wxButton setImage:[UIImage imageNamed:@"login_chaticon"] forState:UIControlStateNormal];
        [_wxButton addTarget:self action:@selector(weixinButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
        [_wxButton sizeToFit];
        [_bottomView addSubview:_wxButton];
        
    }



    _wbButton = [DGAlignmentButton buttonWithType:UIButtonTypeCustom];
//    _wbButton.spacing = 10;
//    _wbButton.backgroundColor = BLUE;
//    _wbButton.frame = CGRectMake(2*iconW, 0, iconW, h);
//    _wbButton.style = DGAlignmentButtonStyleImageLeft;
//    _wbButton.contentEdgeInsets = UIEdgeInsetsMake(6, 6, 6, 6);
//    _wbButton.titleLabel.font = [UIFont systemFontOfSize:12];
//    [_wbButton setTitle:@"微博登录" forState:UIControlStateNormal];
//    [_wbButton setTitleColor:[UIColor colorWithRGBHex:0x2c3c78] forState:UIControlStateNormal];

    [_wbButton setImage:[UIImage imageNamed:@"login_sinaicon"] forState:UIControlStateNormal];
    [_wbButton addTarget:self action:@selector(weiboButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [_wbButton sizeToFit];
    [_bottomView addSubview:_wbButton];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
    //keyboard
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWasShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillBeHidden:) name:UIKeyboardWillHideNotification object:nil];

}

- (IBAction)forgetPasswordButtonDidPress:(id)sender
{
    [MobClick event:@"2"];
//    [self performSegueWithIdentifier:@"PPRetrieveViewController" sender:nil];
        PPRetrieveViewController *findVc = [[UIStoryboard storyboardWithName:@"Login" bundle:nil] instantiateViewControllerWithIdentifier:@"PPRetrieveViewController"];
    [self.navigationController pushViewController:findVc animated:YES];
}

- (void)didReceiveKeyboardWillChangeFrameNotification:(NSNotification *)notification {
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];

    CGRect rect = [[[UIApplication sharedApplication] keyWindow] convertRect:endRect toView:self.view];

    _keyboardTop = CGRectGetMinY(rect);

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|(curve << 16) animations:^{
//        _bottomView.bottom = _keyboardTop;
    } completion:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    CGFloat h = self.bottomView.height;
    CGFloat w = 70;
  
    self.qqButton.frame = CGRectMake((SCREEN_WIDTH-100)/2-w/2, 0, w, h);
    
    self.wxButton.frame = CGRectMake(_qqButton.frame.origin.x-w-30, 0, w, h);
    self.wbButton.frame = CGRectMake(CGRectGetMaxX(_qqButton.frame)+30, 0, w, h);
//    _loginButton.frame = CGRectMake(0, _bottomView.height - 45, _bottomView.width, 45);

//    CGFloat offset = 12;

//    if(_wxButton != nil) {
//        _wxButton.left = offset;
////        _wxButton.bottom = _loginButton.top - 4;
//
//        offset += _wxButton.width + 21;
//    }

//    _qqButton.left = offset;
//    _qqButton.bottom = _loginButton.top - 4;
//    offset += _qqButton.width + 21;

//    _wbButton.left = offset;
//    _wbButton.bottom = _loginButton.top - 4;
}

///MARK:登录
- (void)loginButtonDidPressed {

    [MobClick event:@"6"];

//    if(!_loginButton.enabled) {
//        return;
//    }



    if (_accountField.text.length <= 0 || [_accountField.text isEqualToString:@""]) {
          [self.navigationController.view toastMessage:@"请输入账号"];
        return;
    }
    if (_passwordField.text.length <= 0 || [_passwordField.text isEqualToString:@""]) {
        [self.navigationController.view toastMessage:@"请输入密码"];
        
        return;
    }
    [self.view endEditing:YES];
    
    NSString *username = _accountField.text;
    NSString *password = _passwordField.text;

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    __weak typeof(self) weakSelf = self;
    [PPNetworkService loginWithLoginType:@(0) phoneNumber:username password:password callback:^(id data, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(strongSelf == nil)
        {
            return;
        }

        [hud hide:YES];

        if(error == nil) {
            DGAccount *account = [[DGAccount alloc] init];
            account.userID = [data validStringForKey:@"user"];
            account.username = username;
            account.password = password;
            account.credential = [[DGAccountCredential alloc] init];
            account.credential.userID = account.userID;
            account.pickpic =data[@"pickpic"];
            account.name = data[@"name"];
            account.credential.token = [data validStringForKey:@"token"];
           
            
            
            NSDictionary *dict = data;
            
            [[PPUserAccount yy_modelWithDictionary:dict] saveAccount];
            
            [[PPAccountManager sharedInstance] loginWithAccount:account completion:^(BOOL success) {
//                if(success) {
                 account.phone = self.accountField.text;
                    [strongSelf.navigationController.view toastMessage:@"登录成功" duration:1 completion:^{
                        PPHomeViewController *homeViewController = [[PPHomeViewController alloc] init];
                        PPBaseNavigationViewController *navigationController = [[PPBaseNavigationViewController alloc] initWithRootViewController:homeViewController];
                        [[[UIApplication sharedApplication] delegate] window].rootViewController = navigationController;
                    }];
//                } else {
//                    [strongSelf.navigationController.view toastMessage:@"登录失败"];
//                }
            }];
        } else {
            [strongSelf.navigationController.view toastMessage:error.networkPrompt];
        }
    }];

}

- (void)weixinButtonDidPressed {

    [MobClick event:@"3"];

    __weak typeof(self) weakSelf = self;
    [[PPSocializationManager sharedInstance] login:PPSocializationTypeWeixin completion:^(PPSocializationType type, PPSocializationUserObject *user, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(strongSelf == nil)
        {
            return;
        }

        [strongSelf loginWithSocializationType:type user:user error:error];
    }];
    
}

- (void)qqButtonDidPressed {
    [MobClick event:@"4"];

    __weak typeof(self) weakSelf = self;
    [[PPSocializationManager sharedInstance] login:PPSocializationTypeQQ completion:^(PPSocializationType type, PPSocializationUserObject *user, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(strongSelf == nil)
        {
            return;
        }

        [strongSelf loginWithSocializationType:type user:user error:error];
    }];
}

- (void)weiboButtonDidPressed {
    [MobClick event:@"5"];
    __weak typeof(self) weakSelf = self;
    [[PPSocializationManager sharedInstance] login:PPSocializationTypeWeibo completion:^(PPSocializationType type, PPSocializationUserObject *user, NSError *error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        if(strongSelf == nil)
        {
            return;
        }

        [strongSelf loginWithSocializationType:type user:user error:error];
    }];
}

- (void)hiddenButtonDidPressed:(UIButton *)button {
    button.selected = !button.selected;

    _passwordField.secureTextEntry = !button.selected;
}

- (void)loginWithSocializationType:(PPSocializationType)type user:(PPSocializationUserObject *)user error:(NSError *)error {
    if(error == nil) {

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

        __weak typeof(self) weakSelf = self;
        [PPNetworkService loginFromThirdWithThirdPartyID:user.loginID source:@(type) name:user.name avatar:user.avatar gender:@(user.gender) city:user.city state:user.province callback:^(id data, NSError *error) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            if(strongSelf == nil)
            {
                return;
            }

            [hud hide:YES];

            if(error == nil) {

                DGAccount *account = [[DGAccount alloc] init];
                account.userID = [data validStringForKey:@"user"];
                account.username = @"三方登录用户";
                account.credential = [[DGAccountCredential alloc] init];
                account.credential.userID = account.userID;
                account.credential.token = [data validStringForKey:@"token"];
                account.user3rdURL = user.avatar;
                account.pickpic =data[@"pickpic"];
                account.name = data[@"name"];
                
                NSDictionary *dict = data;
                [[PPUserAccount yy_modelWithDictionary:dict] saveAccount];
                
                NSString *souce;
                if (type == PPSocializationTypeWeixin) {
                    souce = @"2";
                }else if (type == PPSocializationTypeQQ){
                    souce = @"4";
                }else if(type == PPSocializationTypeWeibo){
                    souce = @"8";
                }else{
                    souce = @"99";
                }
                [PPUserAccount updateAccountInfoKey:@"source" value:souce];
                
                [[PPAccountManager sharedInstance] loginWithAccount:account completion:^(BOOL success) {
                    
//                    if(success) {
                        PPHomeViewController *homeViewController = [[PPHomeViewController alloc] init];
                        PPBaseNavigationViewController *navigationController = [[PPBaseNavigationViewController alloc] initWithRootViewController:homeViewController];
                        [[[UIApplication sharedApplication] delegate] window].rootViewController = navigationController;
//                    } else {
//                        [strongSelf.view toastMessage:@"登录失败"];
//                    }
                }];

            } else {
                [strongSelf.navigationController.view toastMessage:error.networkPrompt];
            }
        }];

    } else {
        [self.navigationController.view toastMessage:error.networkPrompt];
    }
}
#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if([string isEqualToString:@"\n"]) {
        if(textField == _accountField) {
            [_passwordField becomeFirstResponder];
        } else {
            [_passwordField resignFirstResponder];
        }

        return NO;
    }

    NSString *account = _accountField.text;
    NSString *password = _passwordField.text;

    if(textField == _accountField) {
        account = [account stringByReplacingCharactersInRange:range withString:string];
    } else {
        password = [password stringByReplacingCharactersInRange:range withString:string];
    }

//    _loginButton.enabled = (account.length > 0 && password.length > 0);

    return YES;
}


//MARK:键盘
- (void)keyBoardWasShow:(NSNotification *)notice{
    NSDictionary *dict=notice.userInfo;
    //获取时间
    self.time = [dict[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    //动画曲线
    self.curve = [dict[UIKeyboardAnimationCurveUserInfoKey] integerValue];
    //键盘高度
    self.keyboardHeight = [dict[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    
//    [UIView animateWithDuration:self.time animations:^{
//        //曲线
//        [UIView setAnimationCurve:self.curve];
//        self.bottomView.transform=CGAffineTransformMakeTranslation(0,-self.keyboardHeight);
//    }];
}
- (void)keyboardWillBeHidden:(NSNotification *)notice{
    
//    [UIView animateWithDuration:self.time animations:^{
//        //曲线
//        [UIView setAnimationCurve:self.curve];
//        self.bottomView.transform=CGAffineTransformIdentity;
//    }];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    
    if (textField == _accountField) {
         [_passwordField becomeFirstResponder];
    }else{
    
        [_accountField resignFirstResponder];
        
        [self loginButtonDidPressed];
    }
    
    return YES;
}
@end
